package com.thoughtworks.biblioteca;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Formatter;

import com.thoughtworks.biblioteca.exceptions.IllegalSelectionNumberException;
import com.thoughworks.biblioteca.utils.HelperUtil;

/**
 * The class to start the application.
 */
public class Program {
    private final static String MENU_HEAD = "**********************************************************\n* Welcome to The Bangalore Public Library System - Biblioteca *\n**********************************************************\n*                Menu                                    *\n*         =====================                          *";
    private final static String MENU_FOOT = "\n**********************************************************";

    public static void printMenu(Menu menu) {
        StringBuffer menuString = new StringBuffer(MENU_HEAD);
        for (Integer itemNumber : menu.getMenuItems().keySet()) {
            Formatter formatter = new Formatter();
            formatter.flush();
            formatter.format("%-47s", itemNumber + ". "
                    + menu.getMenuItemAt(itemNumber).toString());
            menuString.append("\n*         " + formatter.toString() + "*");
        }
        menuString.append(MENU_FOOT);
        System.out.println(menuString.toString());
    }

    public static void main(String[] args) {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(System.in));
        Menu menu = new Menu();
        while (true) {
            printMenu(menu);
            System.out.println("Your Selection: ");
            try {
                int selection = HelperUtil.getInput(bufferedReader);
                menu.executeAfterSelectionItem(selection);
            } catch (IllegalSelectionNumberException e) {
                System.out.println(e.getMessage());
            }
        }
    }

}
